// pages/master/mainten/famMainten/childMedHistory/addHistory/addHistory.js
const app = getApp();
var util = require("../../../../../utils/util.js")

const db = wx.cloud.database()
const _ = db.command

// var fnum=null
// var cname=null
var publishPicture =[] 

Page({

  /**
   * 页面的初始数据
   */
  data: {
    temPicture:[],
    value:0,
    storeID:null,
    id_id:null
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.id)
    // fnum=options.famnum
    // cname = options.childName
    this.setData({
      storeID:options.sid,
      id_id:options.id
    })
  },

  onChange:function(e){
      console.log(e.detail)
      this.setData({
        value:e.detail
      })
  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  //添加图片
  addPicture:function(){
    let that = this
    wx.chooseImage({
            count: 3-that.data.temPicture.length, //最多选择三张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                console.log(res)
                var tempFiles = res.tempFiles
                  tempFiles.forEach((eachFile,index)=>{
                      that.data.temPicture =  that.data.temPicture.concat(eachFile.path)
                      if(that.data.temPicture.length>=3){
                        that.setData({
                          addpic_hidden:true
                        })
                      }
                      that.setData({
                        temPicture: that.data.temPicture
                      })
                  }
              )
            }
          })
  },

  previewImage: function (e) {
    app.previewImage(e)
  },

  //删除图片  （点击红叉叉）
  deletePicture:function(e){
    let that = this
    let picid = e.currentTarget.id
    console.log(e.currentTarget.id)
      wx.showModal({
        title: '',
        content: '要删除这张照片吗？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.data.temPicture.splice(that.data.temPicture.findIndex(e => e === picid), 1) 
            that.setData({
              temPicture: that.data.temPicture,
              addpic_hidden:false
            })
            console.log(that.data.temPicture)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
  },

  //上传图片到云存储
  uploadPicture:function(fileUrl,cloudUrl){
    let that = this
    that.data.temPicture.forEach((item,i)=>{      
      wx.cloud.uploadFile({
          cloudPath: String(cloudUrl)+i+'.jpg', // 上传至云端的路径
          filePath: fileUrl[i], // 小程序临时文件路径
          success: res => {
            console.log(res.fileID)
            publishPicture.push(res.fileID)
            upsuccess = true
          },
          fail: res => {
            upsuccess = false
          }
        })
    })
  },
  clickSure:function(e){
    console.log(e)
},
  clickSure:function(e){
    console.log(e)
      wx.showLoading()
      let that = this
      let _sid = that.data.storeID
      let _id =that.data.id_id
      let _rate=  e.detail.value.rate
      let _content = e.detail.value.conmentContent
      let _phone = app.userDate.userInfo.userPhone
console.log(_sid,_rate,_content)
      if(_content==""){
        wx.showToast({
          title: '你还未评价!',
          icon:'none'
        })
      }else{
        if(_content==""){
          wx.showToast({
            title: '你还未评分!',
            icon:'none'
          })
        }else{
          let imgid = _sid+_phone+new Date().getTime()//app.userDate.userInfo.userPhone
          // console.log(publishid)
           let promiseMethod = new Array(that.data.temPicture.length)
           that.data.temPicture.forEach((item,i)=>{
                   promiseMethod[i] = wx.cloud.uploadFile({
                       cloudPath: String(imgid)+i+'.jpg',
                       filePath: that.data.temPicture[i]
                   }).then(res => {
                     publishPicture.push(res.fileID)
                   })
               })
       
           Promise.all([...promiseMethod]).then(() => {
            wx.cloud.callFunction({
              name:'updateStoresComment',
              data:{
                id:_sid,
                content:_content,
                date:util.formatDate(new Date()),
                img:publishPicture,
                rate:_rate
              }
            }).then(res=>{
              console.log(res)
              if(res.result.errMsg == "collection.update:ok"){
        //         .userid,
        // OrderID:event.orderid,

        wx.cloud.callFunction({
          name:'updateOrderData',
          data:{
            type:'user',
            userid:_phone,
            orderid:_sid,
            id:_id
          }
        }).then(res=>{
          console.log(res)
          if(res.result.errMsg == "collection.update:ok"){
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '评价成功!',
                  icon:'success'
                })
                var pages = getCurrentPages() 
                var currentPage = pages[pages.length-2] 
                currentPage.getUnEvaluateOrder()                 
                wx.navigateBack()
              },
            })
          }else{
            wx.showToast({
              title: '评价出错，请稍后重试~',
            })
          }
        })
                
              }else{
                wx.showToast({
                  title: '评价出错，请稍后重试~',
                })
              }
            })
           })
        }
      }
       
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})